package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.util.StrUtil;
import com.tbit.common.entity.view.Result;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.ComparatorDate;
import com.tbit.uqbike.object.pojo.OutAge;
import com.tbit.common.entity.pojo.dto.OutAgeDTO;
import com.tbit.uqbike.service.business.OutAgeService;
import com.tbit.uqbike.webmanager.dao.core.OutAgeDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 一键停运service
 *
 * @author <a href="mailto:liu.haoxiang@tbit.com.cn">BUGXiang</a>
 * @version 1.0
 * @since 2025-1-22
 */
@Service
@Slf4j
public class OutAgeServiceImpl implements OutAgeService {

    @Resource
    private OutAgeDao outAgeDao;


    /**
     * 查询一键停运信息
     *
     * @param dto 查询参数
     * @return OutAge
     */
    @Override
    public Result<OutAge> queryOutAge(OutAgeDTO dto) {
        return Result.success(outAgeDao.queryOutAge(dto));
    }


    /**
     * 编辑一键停运信息
     *
     * @param outAge 一键停运信息
     * @return Result
     */
    @Override
    public Result<Object> addOrUpdate(OutAge outAge) {
        if (Objects.isNull(outAge.getBrandId()) && Objects.isNull(outAge.getAccountId())) {
            return Result.error("请选择品牌或区域");
        }
        //校验公告标题和内容长度
        if (Objects.nonNull(outAge.getAnnouncementTitle()) && outAge.getAnnouncementTitle().length() > 9) {
            return Result.error("公告标题长度不能超过9个字符");
        }
        if (Objects.nonNull(outAge.getAnnouncementContent()) && outAge.getAnnouncementContent().length() > 200) {
            return Result.error("公告内容长度不能超过200个字符");
        }

        /*校验时间段是否冲突*/
        if (StrUtil.isNotBlank(outAge.getShowdownTimePeriod())){
            checkShowdownTimePeriod(formatTimeToHHmm(outAge.getShowdownTimePeriod()));
        }

        outAge.setShowdownEndTime(getEndOfDay(outAge.getShowdownEndTime()));
        outAge.setAnnouncementEndTime(outAge.getShowdownEndTime());
        if (Objects.isNull(outAgeDao.queryOutAge(new OutAgeDTO(outAge.getBrandId(), outAge.getAccountId())))) {
            //新增
            outAgeDao.insert(outAge);
        } else {
            //更新
            outAgeDao.edit(outAge);
        }
        return Result.success();
    }


    /**
     * 删除一键停运信息
     *
     * @param brandId   品牌id
     * @param accountId 区域id
     */
    @Override
    public void deleteByAccountId(Integer brandId, Integer accountId) {
        if (Objects.isNull(brandId) && Objects.isNull(accountId)) {
            log.error("删除一键停运信息失败，参数为空");
            return;
        }
        outAgeDao.deleteByAccountId(brandId, accountId);
    }

    /**
     * 获取指定日期当天的最后时间 (23:59:59.999)
     *
     * @param date 指定日期
     * @return 当天的最后时间
     */
    private Date getEndOfDay(Date date) {
        if (Objects.isNull(date)) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }


    private void checkShowdownTimePeriod(List<ComparatorDate> timeList) {
        timeList.sort(Comparator.comparingInt(ComparatorDate::getStart));
        // 遍历相邻时间段，看是否有重叠
        for (int i = 1; i < timeList.size(); i++) {
            if (timeList.get(i - 1).getEnd() > timeList.get(i).getStart()) {
                throw new BaseException("时间段冲突");
            }
        }
    }


    /**
     * 将时间字符串格式化为 HHmm 格式的字符串
     *
     * @param timeStr 时间字符串 (例如 "08:00:00")
     * @return HHmm 格式的字符串 (例如 "080000")
     * @throws ParseException 如果时间字符串格式不正确
     */
    private List<ComparatorDate> formatTimeToHHmm(String timeStr) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("HHmmss");
        List<ComparatorDate> list = new ArrayList<>();
        try {
            String[] split = timeStr.split(",");
            for (String s : split) {
                String[] timePeriod = s.split("-");
                ComparatorDate comparatorDate = new ComparatorDate(
                        Integer.parseInt(outputFormat.format(inputFormat.parse(timePeriod[0]))),
                        Integer.parseInt(outputFormat.format(inputFormat.parse(timePeriod[1])))
                );
                list.add(comparatorDate);
            }
        } catch (Exception e) {
            log.error("日期格式化异常", e);
        }
        return list;
    }

}
